package cn.cdm.controller;

import cn.cdm.entity.BaseResponse;
import cn.cdm.entity.dto.RedPacketDto;
import cn.cdm.entity.enums.StatusCode;
import cn.cdm.service.RedPacketService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * @author: zhonglinsen
 * @date: 2019/3/15
 */
@Slf4j
@RestController
public class RedPacketController {

    private static final String prefix="middleware/red/packet";

    @Autowired
    private RedPacketService redPacketService;

    /**
     * 发
     * 发红包接口，前端获取到红包全局唯一标识串redId，存入localStorage。用户抢红包时，前端从localStorage中进行取值
     */
    @RequestMapping(value = prefix+"/hand/out",method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseResponse handOut(@Validated @RequestBody RedPacketDto dto, BindingResult result){
       if (result.hasErrors()){
           return new BaseResponse(StatusCode.InvalidParams);
       }
       BaseResponse response=new BaseResponse(StatusCode.Success);
       try {
            String redId=redPacketService.handOut(dto);
            response.setData(redId);
            log.info("userId = {} 发红包成功！", dto.getUserId());

       }catch (Exception e){
           log.error("发红包发生异常：dto={} ",dto,e.fillInStackTrace());
           response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
       }
       return response;
    }


    /**
     * 抢
     * userId 表示哪个用户来抢红包
     * 前端需要知道整个红包的全局唯一标识，但前端的这个唯一标识从哪里来的，前端从localStorage中取该redId
     */
    @RequestMapping(value = prefix+"/rob",method = RequestMethod.GET)
    public BaseResponse rob(@RequestParam Integer userId, @RequestParam String redId){
        BaseResponse response=new BaseResponse(StatusCode.Success);
        try {
            // 调用抢红包的函数，返回的金额以“元”为单位
            BigDecimal result=redPacketService.rob(userId,redId);
            if (result!=null){
                response.setData(result);
            }else{
                response=new BaseResponse(StatusCode.Fail.getCode(),"红包已被抢完!");
            }
        }catch (Exception e){
            log.error("抢红包发生异常：userId={} redId={}",userId,redId,e.fillInStackTrace());
            response=new BaseResponse(StatusCode.Fail.getCode(),e.getMessage());
        }
        return response;
    }
}
























